import { loginApi, getUserProfileApi } from '@/api/user'
import { setToken as setTokenToCookle, getToken, removeToken } from '@/utils/auth'
const state = {
  // 定义token
  token: getToken() || '',
  userInfo: {}
}
const mutations = {
  // 登录
  setToken(state, val) {
    state.token = val
    // 将token 存储在cookle
    setTokenToCookle(val)
  },
  // 获取个人信息
  setUserInfo(state, val) {
    state.userInfo = val
  },
  // 退出
  logOut(state) {
    state.token = ''
    state.userInfo = {}
    removeToken()
  }
}
const actions = {
  // 发起登录请求，保存token
  async login(context, data) {
    const res = await loginApi(data)
    context.commit('setToken', res.data.token)
    return res
  },
  // 获取用户信息
  async getUserProfile(context) {
    const res = await getUserProfileApi()
    context.commit('setUserInfo', res.data)
    return res.data
  }
}
const getters = {}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}

